package link.xieyu.service;

import link.xieyu.mapper.AppArticleMapper;
import link.xieyu.mapper.AppArticlePhotoMapper;
import link.xieyu.pojo.AppArticle;
import link.xieyu.pojo.AppArticlePhoto;
import link.xieyu.pojo.AppUsers;
import link.xieyu.pojo.BadRequestException;
import link.xieyu.pojo.bo.AppContextBO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author xieyu
 */
@Service
@RequiredArgsConstructor
public class ContextServiceImpl implements ContextService {
    private final AppArticleMapper appArticleMapper;
    private final AppArticlePhotoMapper appArticlePhotoMapper;
    private final UsersService usersService;

    @Override
    public void create(AppContextBO appContextBO) {
        AppUsers users = usersService.findById(appContextBO.getUserId());
        if (users.getIsCreate() == 1) {
            throw new BadRequestException("该用户不是作者，无法发帖，请联系客服!");
        }
        int i = appArticleMapper.insertSelective(appContextBO);
        if (appContextBO.getArticlePhotos() == null || appContextBO.getArticlePhotos().size() == 0) {
            return;
        }
        List<AppArticlePhoto> collect =
                appContextBO.getArticlePhotos().stream().peek(e -> e.setArticle(i)).collect(Collectors.toList());
        appArticlePhotoMapper.batchInsert(collect);
    }

    @Override
    public void update(AppContextBO appContextBO) {
        appArticleMapper.updateByPrimaryKeySelective(appContextBO);
        if (appContextBO.getArticlePhotos() == null || appContextBO.getArticlePhotos().size() == 0) {
            return;
        }
        appArticlePhotoMapper.updateBatchSelective(appContextBO.getArticlePhotos());
    }
}
